import { request } from '@/utils/request'

// 知识库文件接口
export interface KnowledgeFile {
  id: string
  title: string
  filename: string
  file_path: string
  file_size: number
  mime_type: string
  file_type: 'document' | 'image' | 'video' | 'audio' | 'other'
  format: string
  folder_id?: string
  folder_name?: string
  tags: string[]
  description?: string
  project_id?: string
  project_name?: string
  author_id: string
  author_name?: string
  author_avatar?: string
  organization_id?: string
  is_public: boolean
  permission: 'public' | 'team' | 'private'
  download_count: number
  view_count: number
  favorite_count: number
  status: string
  created_at: string
  updated_at: string
  is_favorited?: boolean
}

export interface KnowledgeFolder {
  id: string
  name: string
  parent_id?: string
  project_id?: string
  project_name?: string
  description?: string
  author_id: string
  author_name?: string
  organization_id?: string
  permission: 'public' | 'team' | 'private'
  file_count: number
  created_at: string
  updated_at: string
  children?: KnowledgeFolder[]
}

export interface KnowledgeShare {
  id: string
  file_id: string
  token: string
  share_url: string
  allow_download: boolean
  expires_at?: string
  access_count: number
  max_access_count?: number
  has_password: boolean
  created_by: string
  created_at: string
  is_active: boolean
}

export interface KnowledgeComment {
  id: string
  file_id: string
  user_id: string
  user_name?: string
  user_avatar?: string
  content: string
  parent_id?: string
  created_at: string
  updated_at: string
}

// 查询参数
export interface KnowledgeFileQueryParams {
  page?: number
  size?: number
  search?: string
  file_type?: string
  format?: string
  project_id?: string
  folder_id?: string
  tags?: string[]
  sort_by?: string
  sort_order?: 'asc' | 'desc'
}

// 文件列表响应
export interface KnowledgeFileListResponse {
  items: KnowledgeFile[]
  total: number
  page: number
  size: number
  total_pages: number
}

// 创建文件参数
export interface CreateKnowledgeFileParams {
  title: string
  description?: string
  folder_id?: string
  project_id?: string
  tags?: string[]
  permission?: 'public' | 'team' | 'private'
  is_public?: boolean
}

// 更新文件参数
export interface UpdateKnowledgeFileParams {
  title?: string
  description?: string
  folder_id?: string
  project_id?: string
  tags?: string[]
  permission?: 'public' | 'team' | 'private'
  is_public?: boolean
}

// 创建文件夹参数
export interface CreateKnowledgeFolderParams {
  name: string
  parent_id?: string
  project_id?: string
  description?: string
  permission?: 'public' | 'team' | 'private'
}

// 创建分享参数
export interface CreateKnowledgeShareParams {
  allow_download?: boolean
  expires_in_hours?: number
  max_access_count?: number
  password?: string
}

// 创建评论参数
export interface CreateKnowledgeCommentParams {
  content: string
  parent_id?: string
}

// 获取文件列表
export const getKnowledgeFiles = (params?: KnowledgeFileQueryParams) => {
  return request.get<KnowledgeFileListResponse>('/knowledge/files', {
    params
  })
}

// 获取文件详情
export const getKnowledgeFile = (id: string) => {
  return request.get<KnowledgeFile>(`/knowledge/files/${id}`)
}

// 上传文件
export const uploadKnowledgeFile = (formData: FormData) => {
  // 注意：使用FormData时，不要手动设置Content-Type，让浏览器自动设置（包含boundary）
  return request.post<KnowledgeFile>('/knowledge/files/upload', formData)
}

// 更新文件
export const updateKnowledgeFile = (id: string, data: UpdateKnowledgeFileParams) => {
  return request.put<KnowledgeFile>(`/knowledge/files/${id}`, data)
}

// 删除文件
export const deleteKnowledgeFile = (id: string) => {
  return request.delete(`/knowledge/files/${id}`)
}

// 批量删除文件
export const batchDeleteKnowledgeFiles = (ids: string[]) => {
  return request.post('/knowledge/files/batch-delete', { ids })
}

// 下载文件
export const downloadKnowledgeFile = (id: string) => {
  return request.get(`/knowledge/files/${id}/download`, {
    responseType: 'blob'
  })
}

// 获取文件夹列表
export const getKnowledgeFolders = (params?: {
  project_id?: string
  tree?: boolean
}) => {
  return request.get('/knowledge/folders', {
    params
  }).then(res => res.data)
}

// 创建文件夹
export const createKnowledgeFolder = (data: CreateKnowledgeFolderParams) => {
  return request.post<KnowledgeFolder>('/knowledge/folders', data)
}

// 更新文件夹
export const updateKnowledgeFolder = (id: string, data: Partial<CreateKnowledgeFolderParams>) => {
  return request.put<KnowledgeFolder>(`/knowledge/folders/${id}`, data)
}

// 删除文件夹
export const deleteKnowledgeFolder = (id: string) => {
  return request.delete(`/knowledge/folders/${id}`)
}

// 创建分享链接
export const createKnowledgeShare = (fileId: string, data?: CreateKnowledgeShareParams) => {
  return request.post<KnowledgeShare>(`/knowledge/files/${fileId}/share`, data || {})
}

// 获取分享信息
export const getKnowledgeShare = (fileId: string) => {
  return request.get<KnowledgeShare | null>(`/knowledge/files/${fileId}/share`)
}

// 撤销分享链接
export const revokeKnowledgeShare = (fileId: string) => {
  return request.delete(`/knowledge/files/${fileId}/share`)
}

// 通过分享令牌获取文件
export const getKnowledgeFileByShareToken = (token: string, password?: string) => {
  return request.get<{ file: KnowledgeFile; share: KnowledgeShare }>(`/knowledge/share/${token}`, {
    params: { password }
  })
}

// 通过分享令牌下载文件
export const downloadKnowledgeFileByShareToken = (token: string, password?: string) => {
  return request.get(`/knowledge/share/${token}/download`, {
    params: { password },
    responseType: 'blob'
  })
}

// 添加评论
export const createKnowledgeComment = (fileId: string, data: CreateKnowledgeCommentParams) => {
  return request.post<KnowledgeComment>(`/knowledge/files/${fileId}/comments`, data)
}

// 获取评论列表
export const getKnowledgeComments = (fileId: string) => {
  return request.get<KnowledgeComment[]>(`/knowledge/files/${fileId}/comments`)
}

// 收藏文件
export const favoriteKnowledgeFile = (id: string) => {
  return request.post(`/knowledge/files/${id}/favorite`)
}

// 取消收藏
export const unfavoriteKnowledgeFile = (id: string) => {
  return request.delete(`/knowledge/files/${id}/favorite`)
}

// 获取收藏列表
export const getFavoriteKnowledgeFiles = (params?: {
  page?: number
  size?: number
}) => {
  return request.get<KnowledgeFileListResponse>('/knowledge/files/favorites', {
    params
  })
}

// 获取文件预览信息
export const getKnowledgeFilePreview = (id: string) => {
  return request.get<{ 
    preview_url: string
    preview_type: 'text' | 'pdf' | 'image' | 'excel' | 'word' | 'ppt' | 'video' | 'audio' | 'url'
    is_editable: boolean
    file: KnowledgeFile 
  }>(`/knowledge/files/${id}/preview`)
}

// 获取文件内容（文本类文件）
export const getKnowledgeFileContent = (id: string) => {
  return request.get<{ content: string }>(`/knowledge/files/${id}/content`)
}

// 保存文件内容（文本类文件）
export const saveKnowledgeFileContent = (id: string, content: string) => {
  return request.put<KnowledgeFile>(`/knowledge/files/${id}/content`, { content })
}

// 获取知识库统计信息
export interface KnowledgeStats {
  total_files: number
  total_folders: number
  total_size: number
  files_by_type: Record<string, number>
  files_by_format: Record<string, number>
  recent_files: Array<{
    id: string
    title: string
    filename: string
    file_size: number
    file_type: string
    format: string
    created_at: string
  }>
  popular_files: Array<{
    id: string
    title: string
    filename: string
    file_size: number
    file_type: string
    format: string
    created_at: string
  }>
}

export const getKnowledgeStats = (params?: {
  project_id?: string
}) => {
  return request.get<KnowledgeStats>('/knowledge/stats', {
    params
  })
}

